package org.example.ssl;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

@Configuration
public class TrustAllConnFactory {
//    @Value("${ok-http.connect-timeout}")
//    private Integer connectTimeout;
//    @Value("${ok-http.read-timeout}")
//    private Integer readTimeout;
//    @Value("${ok-http.write-timeout}")
//    private Integer writeTimeout;
//    @Value("${ok-http.max-idle-connections}")
//    private Integer maxIdleConnections;
//    @Value("${ok-http.keep-alive-duration}")
//    private Long keepAliveDuration;

    public ClientHttpRequestFactory build() {
        ClientHttpRequestFactory factory = null;
        try {
            factory = new OkHttp3ClientHttpRequestFactory(okHttpConfigClient());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException(e);
        }

        return factory;
    }

    public OkHttpClient okHttpConfigClient() throws NoSuchAlgorithmException, KeyManagementException {
        return new OkHttpClient().newBuilder()
//                .connectionPool(pool())
//                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
//                .readTimeout(readTimeout, TimeUnit.SECONDS)
//                .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                .hostnameVerifier((hostname, session) -> true)
                .sslSocketFactory(sslFactory(), trustManager())
                // 设置代理
                // .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)))
                // 拦截器
                // .addInterceptor()
                .build();
    }

    /**
     * 信任任何连接, 不去校验证书
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    private SSLSocketFactory sslFactory() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{trustManager()}, new SecureRandom());

        return sslContext.getSocketFactory();
    }

    private X509TrustManager trustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }

//    public ConnectionPool pool() {
//        return new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS);
//    }
}
